package com.gugee.ins.common.dal.spider;

import com.gugee.common.exception.BizException;
import com.gugee.common.exception.SpiderRetryableException;
import com.gugee.ins.common.dal.spider.config.SpiderConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.retry.annotation.Retryable;
import org.springframework.web.client.RestTemplate;

import java.text.MessageFormat;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: luolifeng
 * Date: 2021-01-12 9:50
 */
public class SpiderCommon<T> {
    /**
     * restTemplate
     */
    @Autowired
    RestTemplate restTemplate;

    /**
     * redis
     */
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    /**
     * redis
     */
    @Autowired
    SpiderConfig spiderConfig;

    @Retryable(value = SpiderRetryableException.class, maxAttemptsExpression = "${ins.spider.insBlogger.retry:1}")
    public     T  getForEntity(String url,Class<T> responseType,Object... params ) {
        ResponseEntity<T> responseEntity = restTemplate.getForEntity(url, responseType, params);

        if (responseEntity.getStatusCode() != HttpStatus.OK) {
            throw new BizException(String.format("get insBloggerByUid error. status: %s . msg: %s",
                    responseEntity.getStatusCodeValue(), responseEntity.getBody()),  "BIZ_SPIDER_STATUS_ERROR");
        }
        if (responseEntity.getBody() == null) {
            throw new SpiderRetryableException("get insBloggerByUid error, retry times " + spiderConfig.getSpiderRetryTimes() +  MessageFormat.format(url,params ));
        }
        return responseEntity.getBody();
    }
}
